package com.sdcit.umis.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.sdcit.umis.common.Result;
import com.sdcit.umis.entity.User;
import com.sdcit.umis.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.sql.Wrapper;
import java.util.List;

@RestController
@RequestMapping("/user")
public class UserController {

    @Resource
    private UserMapper userMapper;

    @GetMapping
    public Result findPage(@RequestParam Integer currPageNum,
                           @RequestParam Integer pageSize,
                           @RequestParam String searchWord){
        System.out.println(currPageNum+","+pageSize);
        Page<User> page = new Page<User>(currPageNum, pageSize);
        //List<User> userList = userMapper.selectList(null);
        LambdaQueryWrapper<User> wrapper = Wrappers.<User>lambdaQuery();
        if(StringUtils.isNotBlank(searchWord)){
            wrapper.like(User::getNickName,searchWord);
        }

        Page<User> userPage = userMapper.selectPage(page, wrapper);
        return Result.success(userPage);
    }

    @PostMapping
    public Result save(@RequestBody User user){
        System.out.println(user);
        int result = userMapper.insert(user);
        if(result>0){
            return Result.success();
        }else{
            return Result.error("-1", "保存用户信息失败");
        }

    }

    @PutMapping
    public Result update(@RequestBody User user){
        //使用updateById
        int result = userMapper.updateById(user);
        if(result>0){
            return Result.success();
        }else{
            return Result.error("-1", "修改失败！");
        }
    }

    @DeleteMapping("/{id}")
    public Result delete(@PathVariable("id") Integer id){
        //使用updateById
        int result = userMapper.deleteById(id);
        if(result>0){
            return Result.success();
        }else{
            return Result.error("-1", "删除失败！");
        }
    }

}
